package com.caiwangdai.app.origin.web


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.view.View
import android.webkit.*
import com.caiwangdai.app.BuildConfig
import com.caiwangdai.app.Const
import com.caiwangdai.app.R
import com.caiwangdai.app.backend.cookie.CookieCenter
import com.caiwangdai.app.extension.gone
import com.caiwangdai.app.extension.isEmpty
import com.caiwangdai.app.extension.toast
import com.caiwangdai.app.extension.visible
import com.caiwangdai.app.origin.BaseActivity
import com.caiwangdai.app.origin.ToolBarManager
import com.caiwangdai.app.widget.MultiplyStateViewWM
import com.orhanobut.logger.Logger
import kotlinx.android.synthetic.main.content_universal_web.*
import java.util.*


/**
 * 基本web页面
 */
abstract class BaseWebActiivity : BaseActivity() {
    override fun getLayoutResID() = R.layout.activity_web_normal

    private var isLoading = false//是否正在加载
    private var currentScale: Float = 0.toFloat()//当前页面比例
    private lateinit var targetUrl: String//目标URL
    private lateinit var targetTitle: String//目标标题


    override fun initData() {
        targetUrl = intent.getStringExtra(Const.TARGET_URL)
        targetTitle = intent.getStringExtra(Const.TARGET_TITLE)
    }

    override fun initView() {
        webview.gone()
        initToolBar()
        initWebViews()
    }


    protected fun initToolBar() {
        ToolBarManager.with(this, WMContent)
                .setBackgroundColor(R.color.colorPrimary)
                .setLeftMenuIconRes(R.drawable.ic_nav_arrow_white)
                .setLeftMenuIconClickListener(View.OnClickListener { onBackPressed() })
                .setTitle(targetTitle)
    }


    @SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
    protected fun initWebViews() {

        //normal settings
        val settings = webview!!.settings//
        settings.javaScriptEnabled = true//支持javaScript
        settings.userAgentString = settings.userAgentString + BuildConfig.APPNAME
        settings.allowFileAccess = true//允许访问文件数据
        settings.builtInZoomControls = false//设置支持缩放
        settings.databaseEnabled = true
        settings.setAppCacheEnabled(true)//启用或禁用应用缓存
        settings.domStorageEnabled = true//开启DOM缓存，关闭的话H5自身的一些操作是无效的
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.loadsImagesAutomatically = true//在页面装载完成之后再去加载图片。
        settings.allowUniversalAccessFromFileURLs = true
        settings.loadWithOverviewMode = true
        settings.useWideViewPort = true
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        //sync app cookie
        CookieCenter.getInstance().synCookies(mContext, targetUrl)

        //webview
        webview?.requestFocus()
        webview?.scrollBarStyle = WebView.SCROLLBARS_OUTSIDE_OVERLAY//滚动条样式
        webview?.addJavascriptInterface(JSBridge(mContext), "JSBridge")
        webview?.webViewClient = object : WebViewClient() {

            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                Logger.i("shouldOverrideUrlLoading url=${request?.toString()}")
                return super.shouldOverrideUrlLoading(view, request)
            }


            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                if (isLoading) return
                super.onPageStarted(view, url, favicon)
                Logger.i("onPageStarted ${url}")
                webview.gone()
                beginRefreshAnimation()
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                //js执行完在执行此方法
                Logger.i("onPageFinished ${url}")
                webview.visible()
                endRefreshAnimation()
            }

            override fun onScaleChanged(view: WebView?, oldScale: Float, newScale: Float) {
                super.onScaleChanged(view, oldScale, newScale)
                currentScale = newScale
            }

            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                super.onReceivedSslError(view, handler, error)
                handler?.proceed()//表示等待证书响应
            }


        }
        webview?.webChromeClient = object : WebChromeClient() {

            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                //设置了Alert才会弹出，重新onJsAlert（）方法return true可以自定义处理信息
                Logger.i("onJsAlert")
                return super.onJsAlert(view, url, message, result)
            }
        }

        //check
        if (targetTitle.isEmpty()) {
            toast("url不能为空")
            onBackPressed()
            return
        }

        //load
        loadEverThing(targetUrl)
    }

    fun loadEverThing(str: String) {
        //mWebView.loadUrl("file:///android_asset/XX.html");//本地文件存放在：assets文件中
        val map = HashMap<String, String>()
        //map.put("token", AppData.getToken())
        //check url type and load
        if (str.startsWith("http:") || str.startsWith("https:")) {
            webview?.loadUrl(str, map)
        } else {
            webview?.loadData(str, "text/html", "utf-8")
        }
    }


    //开始刷新动画
    fun beginRefreshAnimation() {
        isLoading = true
        multiView.setViewState(MultiplyStateViewWM.VIEW_STATE_LOADING)
    }

    //结束刷新动画
    fun endRefreshAnimation() {
        isLoading = false
        multiView.setViewState(MultiplyStateViewWM.VIEW_STATE_CONTENT)
    }


    override fun onBackPressed() {
        if (webview!!.canGoBack()) {
            webview!!.goBack()
            return
        }
        super.onBackPressed()
    }

    //防止后台无法释放js导致耗电
    @SuppressLint("SetJavaScriptEnabled")
    override fun onResume() {
        super.onResume()
        webview?.settings?.javaScriptEnabled = true
    }


    override fun onDestroy() {
        super.onDestroy()
        webview?.webViewClient = null
        webview?.settings?.javaScriptEnabled = false
        webview?.stopLoading()
        webview?.removeAllViews()
        webview.destroy()
        releaseAllWebViewCallback()
    }

    //释放访内存
    private fun releaseAllWebViewCallback() {
        try {
            val sConfigCallback = Class.forName("android.webkit.BrowserFrame").getDeclaredField("sConfigCallback")
            if (sConfigCallback != null) {
                sConfigCallback.isAccessible = true
                sConfigCallback.set(null, null)
            }
        } catch (e: NoSuchFieldException) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace()
            }
        } catch (e: ClassNotFoundException) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace()
            }
        } catch (e: IllegalAccessException) {
            if (BuildConfig.DEBUG) {
                e.printStackTrace()
            }
        }

    }


    //js调用android的方法
    inner class JSBridge(val mContext: Context) {

        //样例接口
        @JavascriptInterface
        fun doSomeThing(target: String) {

        }
    }


    //注入JS至WebView
    protected fun injectJavaScripToWebView(jsStr: String) {
        val rs = "javascript:" + jsStr

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webview!!.evaluateJavascript(jsStr, null)
        } else {
            webview!!.loadUrl(rs)
        }
    }


}
